package com.idriver.controller;

import com.idriver.bean.Student;
import com.idriver.service.StudentService;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Date;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;

@WebServlet(name = "AddStudentServlet", urlPatterns = "/addStudent")
public class AddStudentServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");
        String name = request.getParameter("name");
        String sex = request.getParameter("sex");
        String birthday = request.getParameter("birthday");
        String mail = request.getParameter("mail");
        String mark = request.getParameter("mark");

        Student stu = new Student();
        stu.setName(name);
        stu.setSex(sex);
        stu.setBirthday(Date.valueOf(birthday));
        stu.setMail(mail);
        stu.setMark(mark);
        stu.setCreated(Timestamp.valueOf((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new java.util.Date())));

        StudentService service = new StudentService();
        int affectedRow = service.addStudent(stu);
        if (1 == affectedRow) {
            System.out.println("新增学员成功");
            response.sendRedirect("main.jsp");
        } else {
            System.out.println("新增学员失败");
            RequestDispatcher dispatcher = request.getRequestDispatcher("addStudent.jsp");
            dispatcher.forward(request, response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
